﻿<?php
header('Content-type:text/html;charset=utf-8');
use \LaneWeChat\Core\TemplateMessage;

/**
 *	退货
 *  模仿文件 www.12301.cc/admin/wx_refund.php
 *  @param  order_num 订单号
 *  @param  log_id   pft_order_refund 的主键ID
 */
if ($_SESSION['sdtype']!=9) {
    Response('you shall not pass', 102);
}

include_once './func/common.php';
include_once './func/SDKConfig.php';
include_once './func/secureUtil.php';
include_once './func/httpClient.php';
//$ordernum = '1240192';
//goto one;
define('LOG_REQUEST', '/var/www/html/new/d/module/zax/unipay/logs_refund/req_'.date('ymd').'.log');
define('LOG_NAME', '/var/www/html/new/d/module/zax/unipay/logs_refund/err_'.date('ymd').'.log');
define('LOG_NAME_OK', '/var/www/html/new/d/module/zax/unipay/logs_refund/ok_'.date('ymd').'.log');
//goto one;
define('ACTION_MONEY_ADD',0);
define('ACTION_MONEY_CUT',1);

if ($_POST['order_num'] && $_POST['log_id']) {
    include '/var/www/html/wx/wechat/core/db.lib.php';
    $log_id    = $_POST['log_id'];
    $ordernum  = $_POST['order_num'];
    $db = \LaneWeChat\Core\Db::Connect();
    //TODO::根据交易号获取订单数据
    $sql = "SELECT id,aid,ordernum,refund_status,refund_fee,refund_money as total_fee,
            trade_no FROM pft_order_refund WHERE id={$log_id} AND refund_status=0 and sourceT=2 LIMIT 1";
    $stmt = $db->prepare($sql);
    $stmt->execute();
    $refund_data = $stmt->fetch(PDO::FETCH_ASSOC);
    if ($refund_data) {
        $tnum = $refund_data['refund_num'];
        if ($refund_data['refund_status']==1) {
            write_logs("记录已更新不需要重复更新.订单号[{$ordernum}]log_id[{$log_id}]");
            $GLOBALS['le']->close();
            //如果这个退款已经处理，不往下执行
            Response('ok', 200);
        }
        $soap = new SoapClient(null,array(
                "location" => "http://localhost/open/openService/pft_insideMX.php",
                "uri" => "www.16u.com?ac_16u=16ucom|pw_16u=c33367701511b4f6020ec61ded352059|auth_16u=true")
        );
        $xml  = $soap->Order_Globle_Search("", "", "", "", "", "", "", "", "", "", "", "",
            $ordernum, "", "", "", "", "", "", "1", "0", "100", "0", "0",
            "", "0", "", "0", "", "", "", "0", "0");
        $order_arr = simplexml_load_string($xml);
        if (!count($order_arr)) {
            write_logs("Error|[{$ordernum}]|订单数据为空",LOG_NAME);
            $GLOBALS['le']->close();
            Response('订单为空', 100);
        }
        //当是联票时 发送的订单号与之前的重复 银联会报错 所以带上表的ID
        $aid = (int)$order_arr->Rec->UUaid;
        $memo = '';
        $merID = 802350173720081;
//        if($aid==43517){
//            $merID = 943030147330001;
//            $memo = '广西票付通';
//            $_POST['GuangXi_mark'] = 1;
//        }
        $txnTime = $_SERVER['REQUEST_TIME'];
        $params = array(
                'version' => '5.0.0',		//版本号
                'encoding' => 'utf-8',		//编码方式
                'certId' => getSignCertId (),	//证书ID
                'signMethod' => '01',		//签名方法
                'txnType' => '04',		//交易类型
                'txnSubType' => '00',		//交易子类
                'bizType' => '000201',		//业务类型
                'accessType' => '0',		//接入类型
                'channelType' => '07',		//渠道类型
                'orderId' => 'REF'.$ordernum.'R'.$log_id,//为了同个订单多次退票时订单号不重复 R后面附带随机数字
                'merId' => $merID,	//商户代码，请修改为自己的商户号
                'origQryId' => (string)$refund_data['trade_no'],  //原消费的queryId，可以从查询接口或者通知接口中获取
//                'origQryId' =>  '201506031756490822098',
                'txnTime' => date('YmdHis',$txnTime),	//订单发送时间，重新产生，不同于原消费
                'txnAmt' => $refund_data['total_fee'],              //交易金额，退货总金额需要小于等于原消费
                'backUrl' => SDK_REFUND_NOTIFY_URL,	   //后台通知地址
                'reqReserved' =>' 透传信息', //请求方保留域，透传字段，查询、通知、对账文件中均会原样出现
            );

        sign($params);
        write_logs(json_encode($params),LOG_REQUEST);

        $result = sendHttpRequest ( $params, SDK_BACK_TRANS_URL );

        //返回结果展示
        $result_arr = coverStringToArray($result);
        if(!verify($result_arr)){
            write_logs($ordernum.'返回验证失败',LOG_REQUEST);
            write_logs($ordernum.'返回验证失败',LOG_NAME);
            $GLOBALS['le']->close();
            Response('chK_fail', 104);
        }
        if($result_arr['respMsg']=='成功[0000000]')
             write_logs($ordernum.'退货成功',LOG_REQUEST);
        else{
            write_logs($ordernum.'退货失败,'.$result_arr['respMsg'],LOG_NAME);
            $GLOBALS['le']->close();
            Response('refund_fail', 104);
        }
        $handler_time = date('Y-m-d H:i:s',$txnTime);
        $sql = "UPDATE pft_order_refund SET refund_status=1,handler_time='$handler_time' WHERE id=$log_id LIMIT 1";
        $db->exec($sql);
//        if($aid!=43517){//刘三姐的不扣钱 买订单的时候也不价钱
            $res = $soap->PFT_Member_Fund_Modify($aid, 0 , $refund_data['total_fee'], ACTION_MONEY_CUT, 0,null,1, 0,$ordernum,$memo);
            write_logs("OK|{$ordernum}|上级供应商扣钱($aid)：{$res}",LOG_REQUEST);
//        }

        $sql = "UPDATE pft_alipay_rec SET status=2 WHERE trade_no='{$refund_data['trade_no']}' LIMIT 1";
        if(($ret=$db->exec($sql)) === false){
            write_logs('Error:' . $sql,LOG_NAME);
        }
        $GLOBALS['le']->close();
        AccessLog($db, $_SESSION['memberID'], 1, "退款|订单号[{$ordernum}],记录ID[{$log_id}]|操作账号[{$_SESSION['account']}]");
        Response('ok', 200);
    }
}


function AccessLog(PDO $db, $mid, $action, $mark){
    $remote_addr = remote_address();// 访问地址
    $ins = <<<SQL
INSERT INTO `pft_access_log` SET `access_time`=now(),`mid`=$mid,
`access_ip`='$remote_addr',`access_action`=$action,`access_note`='$mark'
SQL;
    return $db->exec($ins);
}

function remote_address(){
    if(getenv("HTTP_CLIENT_IP")) return getenv("HTTP_CLIENT_IP");
    if(getenv("HTTP_X_FORWARDED_FOR")) return getenv("HTTP_X_FORWARDED_FOR");
    if(getenv("REMOTE_ADDR")) return getenv("REMOTE_ADDR");
}

function Response($msg, $code){
    $json = '{"code":"'.$code.'", "msg":"'.$msg.'"}';
    exit($json);
}

function write_logs($txt, $file = '/var/www/html/new/d/module/zax/unipay/los_refund/new_refund.log'){
    $fp = fopen($file,"a");
    flock($fp, LOCK_EX);
    fwrite($fp,date("Y-m-d H:i:s").":".$txt."\n");
    flock($fp, LOCK_UN);
    fclose($fp);
}
?>


